define(
	[
		'require'
	],
	function(require){
		function newDateAndTime(dateStr){
			var ds = dateStr.split(" ")[0].split("-");
			var ts = dateStr.split(" ")[1].split(":");
			var r = new Date();
			r.setFullYear(ds[0],ds[1] - 1, ds[2]);
			r.setHours(ts[0], ts[1], ts[2], 0);
			return r;
		}
		//自动补零的方法，num为值，n为长度
		function PrefixInteger(num, n) {
            return (Array(n).join(0) + num).slice(-n);
        }
		var Controller = Ember.Controller.extend({
			needs: ["businessDetail", "businessCenter"],

			business: Ember.computed.alias('controllers.businessDetail.model'),

			pinTimePoint: Ember.computed.alias('controllers.businessDetail.pinTimePoint'),

			businessIdChange: Ember.observer("business.id", function(){
				this.set('keyWord', '');
			}),

			initTime: function(){
		        var ctrl = this;
		        var startDate = ctrl.get("startDate");
		        var endDate = ctrl.get("endDate");
		        if(this.get("clickTimePoint") != null ){
		        	var date = new Date(this.get("clickTimePoint"));
		        	ctrl.set("endDate",new Date(+date+60000));
		        	if((isNaN(startDate))){
		        		ctrl.set("startDate",new Date(+date+60000)-60000);
		        	}else{
		        		ctrl.set("startDate",new Date(+date+60000)-(Math.abs(+endDate-(+startDate))));
		        	}
		        	
		        	
		        	setTimeout(function(){
		        		var startDate = APM.util.formatDate(new Date(+ctrl.get("startDate")), "yyyy/MM/dd H:mm");
		        		var endDate = APM.util.formatDate(new Date(+ctrl.get("endDate")), "yyyy/MM/dd H:mm");
		        		$('#config-demo').val(startDate+' - '+endDate);
		        	});
		        	
		        }else{
		        	var sdate = new Date(new Date() - timeD_value - 60000-60000);
			        sdate.setSeconds(0);
			        sdate.setMilliseconds(0); 
			        ctrl.set("startDate",new Date(+sdate));
			        var edate = new Date(new Date() - timeD_value-60000);
			        edate.setSeconds(0);
			        edate.setMilliseconds(0); 
			        ctrl.set("endDate",new Date(+edate));
		        }
		    },

			clickTimePoint: Ember.computed.oneWay('controllers.businessDetail.clickTimePoint'),

			trackTitle: "交易查询",
			
			isTrue: false,

			typeValue: '',

			channelValue: '',

			keyWord: '',
			trackColumns: [
				{
					headerText: "序号",
					dataKey:"sequence",
					width: 60,
					allowSort: false,
					ensurePxWidth: true,
					
				},
				{
					headerText: "发起时间",
					dataKey:"startTime",
					allowSort: false,
					ensurePxWidth: true,
					cellFormatter: function (args, colume) {
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var date = new Date(args.row.data.startTime);
							var dateFor= APM.util.formatDate(date, "yyyy-MM-dd H:mm:ss");
							dateFor = dateFor +"."+PrefixInteger(new Date(args.row.data.startTime).getMilliseconds(),3);
							var cb = $("<div class='date-text'></div>").text(dateFor);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "交易号",
					dataKey:"code",
					allowSort: false,
					ensurePxWidth: true,
					
				},
				{
					headerText: "交易类型",
					dataKey:"typeName",
					allowSort: false,
					
				},
				{
					headerText: "客户端IP",
					dataKey:"srcIp",
					allowSort: false,
					
				},
				{
					headerText: "服务端",
					dataKey:"dstIp",
					allowSort: false,
					width:120,
					cellFormatter: function (args, colume) {
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var serviceName = args.row.data.serviceName,
								dstIp = args.row.data.dstIp
								data = (serviceName?serviceName:"")+"("+dstIp+")"; 


							if(serviceName){
								var cb = $("<div class=''></div>");
								$("<div class=''>"+serviceName+"</div>").appendTo(cb);
							}else{
								var cb = $("<div class='date-text'></div>");
							}
							
							$("<div class=''>"+dstIp+"</div>").appendTo(cb);
							
							cb.appendTo(args.$container);
							return true;
						}
					}
					
				},
				{
					headerText: "返回码",
					dataKey:"responseCode",
					allowSort: false,
					
				},
				{
					headerText: "响应时间",
					dataKey:"responseTime",
					_fmtType: "transform_time",
					cellFormatter: APM.util.indicatorCellFormatter
					
				},
				{
					headerText: "交易结果",
					dataKey:"result",
					allowSort: false,
					
				}
			],

			alerts: Ember.A(),

			transactionChannel: Ember.A(),

			transactionType:Ember.A(),

			isOnce:true,
			
			keyUpEnent: function(){
				var ctrl = this;
				setTimeout(function(){
					$("#mouseKeyUp").on("keyup",function(event){
						if(event.keyCode == 13){
							ctrl.requireAlerts();
						};
					});
				},0)
				
			},

			valueChange: Ember.observer("channelValue","typeValue",'serviceValue',function(){
				this.requireAlerts();
			}),
		

			requireAlerts: function(params) {
				var ctrl = this,
					serviceId = ctrl.serviceId(),
					channelValue = this.get("channelValue"),
					typeValue = this.get("typeValue"),
					serviceValue = this.get("serviceValue"),
					nodeId = ctrl.get("business").id,
					isTrue = ctrl.get("isTrue");


						
				var startDate = this.get("startDate"),
					endDate = this.get("endDate");
				if(!startDate){
					return;
				}
				if(!endDate){
					return;
				}
				if( isLocalDebugModel ){
					endDate = new Date(2014, 9, 1, 12, 0, 0);
					startDate = new Date(+endDate)
					startDate.setHours(startDate.getHours()-1);
				}
				if(typeValue == "交易类型"){
					typeValue = '';
				}
				if(channelValue == '交易渠道'){
					channelValue = '';
				}
				if(serviceValue == '服务节点'){
					serviceValue = '';
				}
				var params = {
					"appId":ctrl.get("business.id"),
					"keyWord": this.get("keyWord"),
				    "startDate": +startDate,
				    "pageIndex": this.get("pageIndex"),
				    "pageSize": this.get("pageSize"),
					"endDate": +endDate,
					"serviceId":serviceValue,
					"transactionChannel":channelValue,
					"transactionType": typeValue,
					"orderBy": this.get("orderBy"),
					"desc": this.get("desc")
				};
				//开发调试模式参数
				if( isLocalDebugModel ){
					params = undefined;
				}

				return ctrl.store.ajax("GET", "trades/tracking", params)
				.then(function(response){
					var status = response.status;
					if(status != "success"){
						return
					};

					ctrl.set('isData',false);

					var alerts = response.result;
					alerts.forEach(function(node,index){
						node.sequence = index+1;
						if(node.isError){
							node.result = "失败";
						}else{
							node.result = "成功";
 						}
					});		

					if (alerts.length == 0) {
						ctrl.set("pageIndex",0);
						ctrl.set("pageSize",10);
						ctrl.set("totalRows",0);
						ctrl.set("pageCount",0);
					} else {
						ctrl.set("pageIndex",response.meta.pageIndex);
						ctrl.set("pageSize",response.meta.pageSize == 0?10:response.meta.pageSize);
						ctrl.set("totalRows",response.meta.total);
						ctrl.set("pageCount",response.meta.totalPage);
					}
					
					ctrl.set("alerts", alerts);
					return response;
				});
			},
			serviceId: function(){
				var serviceId = this.get("model.id");
				var arrId = serviceId.split('-');
				return serviceId = arrId[arrId.length-1];
			},
			transactionRecord:function(transactionId,params){
				return this.store.ajax("GET","trades/transactionDetail/"+transactionId,params);
			},
			transactionChannelRequireAlerts: function(params){
				return this.store.ajax("GET","transaction/channel",params);
			},
			transactionTypeRequireAlerts: function(params){
				return this.store.ajax("GET","transaction/type",params);
			},
			serviceIdRequireAlerts: function(appId,params){
				return this.store.ajax("GET","applications/"+appId,params);
			},
			mergeTransactionRequireAlerts: function(params){
				return this.store.ajax("GET","trades/tracking/merge",params)
			},
		
			mergeTransaction: Ember.observer('isTrue',function(){
				if(this.get('isTrue')){
					this.requireAlerts();
				}else{	
					this.requireAlerts();
				}
			}),
			offEvent: function(){
				$(document).unbind();
			},
			selectData:function(){
				var ctrl = this;
				var appId = ctrl.get("business.id");
				ctrl.transactionTypeRequireAlerts({
					"appId":appId
				}).then(function(response){
					var applications = response.transcationType;
					applications.forEach(function(node){
						node.name = node.typeName;
					});
					ctrl.set("transactionType",Ember.A(applications));
				});
				ctrl.transactionChannelRequireAlerts({
					"appId":appId
				}).then(function(response){
					var applications = response.transcationChannel;
					ctrl.set("transactionChannel",Ember.A(applications));
				});
				ctrl.serviceIdRequireAlerts(appId,{
					"panelId": overviewOrCenterSwitch
				}).then(function(response){
					var topoNodes = response.application.topoNodes;
					ctrl.set("serviceIdList",Ember.A(topoNodes));
				});
				
			},
			actions: {
				gridSorted: function(e, data, view){
					view.ensureControl(false);
					this.set("orderBy", data.column.dataKey);
					this.set("desc", data.sortDirection=="descending"||undefined);
					this.requireAlerts();
				},
				queryBusinessNum:function(){
					this.set("pageIndex",0);
					this.requireAlerts();
				},
				pageIndexChanged: function(e, data, view){
					var pageNo = data.newPageIndex;
					this.set("pageIndex", pageNo);

					this.requireAlerts();
				},
				trackCellClicked: function(e, args, view){
					var oEvent = e||event;
					var ctrl = this,
						row = args.cell.row(),
						column = args.cell.column(),
						startDate = ctrl.get("startDate"),
						endDate = ctrl.get("endDate");
					if (row && (row.type & $.wijmo.wijgrid.rowType.data)) {

						clearTimeout(ctrl.get("time"));
						ctrl.transactionRecord(row.data.id,{"startDate":+startDate,"endDate":+endDate})
						.then(function(response){
							ctrl.set("curErrorStack",Ember.A(response.performances[0].fields));

							ctrl.set("boolean",false);

							var view = Broada.getView("businessNodeDetailTrackStackDialog");
							var o = view.$();
							o.parent().css({"left":window.screen.width/2-400+"px"});
							o.parent().css({"top":window.screen.height/2-300+"px"});
							ctrl.set("view",o);
							o.parent().removeClass("bounceOutRight animated");
							o.parent().removeClass("bounceInRight animated");
							view.openDialog();
							o.parent().addClass("bounceInRight animated");

							o.parent().on("click",function(event){
								event.stopPropagation();
							});

							var time = setTimeout(function(){
							 	ctrl.set("boolean",true);
							 },1000);

							$(document).on("click",function(){
								 if(!ctrl.get("boolean")){
								 	return;
								 };
								 o.parent().removeClass("bounceInRight animated");
								 o.parent().addClass("bounceOutRight animated");
								 ctrl.set("boolean",false);
							});

						})
						
						 
					}
					
					oEvent.cancelBubble = true;
				},
				closeStack: function(ev){
					var oEvent = ev||event;
					$(".node-track-stack").css({
					 	"-webkit-transform":"translate("+(window.screen.width)+"px, 0px)",
						"-moz-transform":"translate("+(window.screen.width)+"px, 0px)",
						"-ms-transform":"translate("+(window.screen.width)+"px, 0px)",
						"-o-transform":"translate("+(window.screen.width)+"px, 0px)",
						"transform":"translate("+(window.screen.width)+"px, 0px)"
					});
					oEvent.cancelBubble = true;
				},

				timePointChange: function(timeRange){
					this.set("startDate",timeRange.startDate);
					this.set("endDate",timeRange.endDate);
			
					this.requireAlerts();
				},

				timeRangesChange: function(timeRange){
		
					var ctrl = this,
						serviceId = ctrl.serviceId(),
						locationStart = this.get("locationStart");
					var isSelectedTime = ctrl.get("controllers.businessDetail").isSelectedTime;
					
							
					ctrl.set("startDate", timeRange.startDate);
					ctrl.set("endDate", timeRange.endDate);
			

					var view = Broada.getView("businessTimeRangesTopo");
					if(ctrl.get("pinTimePoint") != timeRange.startDate){
						ctrl.set("pinTimePoint", null);
					}

					ctrl.set("pageIndex", 0);
					ctrl.requireAlerts();
					ctrl.selectData();

					$("html").css({"overflow-x":"hidden"});			
				},
				mergeTransactionBox: function(){
					
				},
				mergeTransaction: function(){
					var ctrl = this,
						isTrue = ctrl.get('isTrue');

					if(isTrue){
						ctrl.set('isTrue',false);
					}else{
						ctrl.set('isTrue',true);
					}
				}
			}
		});
	
		APM.BusinessDetailNodedetailTrackController = Controller;

		return Controller;
	}
);	